// 封装首页模块相关的请求actionCreator

import { ApiResponse, Article, Channel } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import { getChannels, setChannels } from '@/utils/channels'
import http from '@/utils/request'
import { hasToken } from '@/utils/token'

// 获取用户频道
export function getUserChannelsActionCreator(): RootThunkAction {
  return async (dispatch) => {
    if (hasToken()) {
      // 登录了， 发送请求获取自己的数据， 发请求操作自己的数据
      const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )

      dispatch({
        type: 'home/set_user_channels',
        payload: res.data.data.channels,
      } as RootAction)
    } else {
      // 没登录，也可以看首页，发请求拿默认数据，操作本地数据

      // 判断本地存储有无数据
      const userChannels = getChannels()
      if (userChannels.length > 0) {
        // 该设备已经在未登录的情况下 访问过网页， 本地有数据
        dispatch({
          type: 'home/set_user_channels',
          payload: userChannels,
        } as RootAction)
      } else {
        // 没有登录， 第一次访问网页
        // 发请求获取默认数据
        const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
          '/user/channels'
        )

        setChannels(res.data.data.channels)
        dispatch({
          type: 'home/set_user_channels',
          payload: res.data.data.channels,
        } as RootAction)
      }
    }
  }
}

// 获取所有频道
export function getAllChannelsActionCreator(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    // console.log(res)
    dispatch({
      type: 'home/set_all_channels',
      payload: res.data.data.channels,
    } as RootAction)
  }
}

// 请求添加频道
export function addChannelActionCreator(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    const userChannels = getState().home.userChannels

    if (hasToken()) {
      // 登录了，操作的是接口中的频道数据
      await http.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      // 没登录， 也可以添加频道， 只不过添加的是本地
      // 老的数据 + channel
      setChannels([...userChannels, channel])
    }

    // 将新增的数据同步到仓库中
    dispatch({
      type: 'home/set_user_channels',
      payload: [...userChannels, channel],
    } as RootAction)
  }
}

// 删除指定频道
export function delChannelActionCreator(id: number): RootThunkAction {
  return async (dispatch, getState) => {
    const userChannels = getState().home.userChannels
    if (hasToken()) {
      // 操作自己的数据
      await http.delete('/user/channels/' + id)
    } else {
      // 操作本地数据
      const resChannels = userChannels.filter((item) => item.id !== id)
      setChannels(resChannels)
    }

    // 获取最新用户频道
    dispatch(getUserChannelsActionCreator())
  }
}

// 上拉加载
export function getArticleListActionCreator(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        // 获取指定频道的文章列表
        channel_id,
        // 获取距离该时间最近的文章列表
        timestamp,
      },
    })
    // console.log(res)
    // res.data.data.results
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/set_channel_articles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    } as RootAction)
  }
}

// 下拉刷新
export function refreshArticleListActionCreator(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        // 获取指定频道的文章列表
        channel_id,
        // 获取距离该时间最近的文章列表
        timestamp,
      },
    })
    // console.log(res)
    // res.data.data.results
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/refresh_channel_articles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    } as RootAction)
  }
}
